package com.yng.simbot01.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebSocket extends WebSocketClient {

    private final List<MessageListener> listeners = new ArrayList<>();

    public WebSocket(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("Connected to server");
    }

    // 注册监听器
    public void addMessageListener(MessageListener listener) {
        listeners.add(listener);
    }
    @Override
    public void onMessage(String message) {
        // You can add additional logic here to handle the message
        // 解析JSON消息
        JSONObject jsonMessage = JSON.parseObject(message);
        String data = jsonMessage.getString("data");
        // 通知所有监听器
        for (MessageListener listener : listeners) {
            listener.onMessageReceived(data);
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("Connection closed with exit code " + code + " and reason: " + reason);
    }

    @Override
    public void onError(Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace(); // Print stack trace for debugging purposes
    }

    public void sendMessage(String message) {
        Map<String, String> map = new HashMap<>();
        map.put("username", "rcc");
        map.put("message", message);
        map.put("role", "user");

        // 将键值对集合转换为JSON字符串
        String jsonString = JSON.toJSONString(map);
        this.send(jsonString);
    }
}
